package com.itheima.youdianda.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.dto.PageDto;
import com.itheima.youdianda.mapper.SysUserMapper;
import com.itheima.youdianda.pojo.SysRole;
import com.itheima.youdianda.pojo.SysUser;
import com.itheima.youdianda.service.SysRoleService;
import com.itheima.youdianda.service.SysUserService;
import com.itheima.youdianda.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public R listSysUser(String loginName, String status, String phone, int page, int limit) {

        Page<SysUser> pageInfo = new Page<SysUser>(Convert.toLong(page), Convert.toLong(limit));
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(loginName),SysUser::getLoginName,loginName);
        wrapper.like(StrUtil.isNotBlank(phone),SysUser::getPhone,phone);
        //status!=null && status!=""
        wrapper.eq(ObjectUtil.isNotEmpty(status),SysUser::getStatus,status);
        pageInfo = page(pageInfo,wrapper);

        //页面中每条sys_user数据
        List<SysUserVo> records = pageInfo.getRecords().stream().map(sysUser -> {
            SysUserVo vo=new SysUserVo();
            //属性值拷贝
            BeanUtil.copyProperties(sysUser,vo);
            //不同的属性单独处理
            vo.setLogin_name(sysUser.getLoginName());
            vo.setCreate_date(sysUser.getCreateDate());
            vo.setUpdate_date(sysUser.getUpdateDate());
            vo.setDefault_data(sysUser.getDefaultData());
            vo.setDel_flag(sysUser.getDelFlag());
            vo.setLogin_ip(sysUser.getLoginIp());
            vo.setLogin_date(sysUser.getLoginDate());

            //roleName提取
            LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
            String roleId = sysUser.getRoleId();
            sysRoleWrapper.in(SysRole::getId,roleId);
            List<SysRole> sysRoles = sysRoleService.list(sysRoleWrapper);
            ArrayList<String> names = new ArrayList<>();
            for (SysRole sysRole : sysRoles) {
                String name = sysRole.getName();
                names.add(name);
            }
            vo.setRolename(names);

            //roleid:根据用户id查询
            String[] roleIds = roleId.replace("[", "").replace("]", "").replace("\"","")
                    .split(",");
            vo.setRole_id(Arrays.asList(roleIds));


            return vo;
        }).collect(Collectors.toList());

        //要返回的最终页面对象
        PageDto pageDto = new PageDto();
        pageDto.setCurrentPage(Convert.toLong(page)); //已有传参:当前页数
        pageDto.setPageSize(Convert.toLong(limit)); //已有传参:每页条数
        pageDto.setCount(pageInfo.getTotal());   //查询结果总条数
        pageDto.setTotalPages(pageInfo.getPages());  //查询结果总页数
        //pageDto.setData(pageInfo.getRecords());
        pageDto.setData(records);

        return R.success(pageDto);
    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public void add(@RequestBody SysUserVo vo) {
        String password = DigestUtils.md5DigestAsHex(vo.getPassword().getBytes());
        vo.setPassword(password);
        vo.setCreate_date(LocalDateTime.now());
        List<String> roleIds = vo.getRole_id();
        //将集合转换为字符串
        String roleId = StringUtils.join(roleIds, ",");

        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo, user);
        //封装数据
        user.setRoleId(roleId);
        user.setLoginName(vo.getLogin_name());
        user.setPassword(password);
        user.setLoginIp(vo.getLogin_ip());
        user.setCreateDate(vo.getCreate_date());
        user.setUpdateDate(vo.getUpdate_date());
        user.setDelFlag(vo.getDel_flag());
        user.setStatus(vo.getStatus());
        user.setDefaultData(vo.getDefault_data());

        save(user);

    }

    @Override
    public R rowInfo(String id) {
        SysUser sysUser = getById(id);
        SysUserVo vo=new SysUserVo();
        //属性值拷贝
        BeanUtil.copyProperties(sysUser,vo);
        //不同的属性单独处理
        vo.setLogin_name(sysUser.getLoginName());
        vo.setCreate_date(sysUser.getCreateDate());
        vo.setDefault_data(sysUser.getDefaultData());
        vo.setDel_flag(sysUser.getDelFlag());
        vo.setLogin_ip(sysUser.getLoginIp());
        vo.setLogin_date(sysUser.getLoginDate());
        //roleid:根据用户id查询
        LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
        String roleId = sysUser.getRoleId();
        sysRoleWrapper.in(SysRole::getId,roleId);

        String[] roleIds = roleId.replace("[", "").replace("]", "").replace("\"","")
                .split(",");
        vo.setRole_id(Arrays.asList(roleIds));

        return R.success(vo);
    }

    @Override
    public void updateSysRole(SysUserVo vo) {
        //处理密码
        String password = vo.getPassword();
        if (password != null) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
        }
        //处理id
        List<String> roleIds = vo.getRole_id();
        String roleId = StringUtils.join(roleIds, ",");
            //封装数据
            SysUser user = new SysUser();
            BeanUtils.copyProperties(vo, user);

            user.setLoginName(vo.getLogin_name());
            user.setPassword(password);
            user.setLoginIp(vo.getLogin_ip());
            user.setCreateDate(vo.getCreate_date());
            user.setUpdateDate(vo.getUpdate_date());
            user.setDelFlag(vo.getDel_flag());
            user.setRoleId(roleId);
            user.setStatus(vo.getStatus());
            user.setDefaultData(vo.getDefault_data());

            //修改数据
            updateById(user);

    }
}
